﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FluentScheduler;
using YiYiTong.Rocket.Helper;
using YiYiTong.Rocket.Business;
using YiYiTong.Rocket.Model;
using YiYiTong.Rocket.EFDBFirst;
using YiYiTong.Rocket.Business.Biz;

namespace YiYiTong.Rocket.ProcessConsole
{
    /// <summary>
    /// 下架提醒
    /// </summary>
    public class WithUpDownJob : BaseJob
    {
        static int excutecounts;
        public override void DoAction()
        {
            if (excutecounts % 1000 == 0)
            {
                LogHelper.Debug($"过期商品，库存卖完商品自动下架处理：{excutecounts}次");
            }
            excutecounts++;

            var exptime = DateTime.Now.AddDays(3);
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            var goodsList =
                (from m in dbcontext.ADZ_GoodsMaster.Where(t => t.is_del == 0 && t.is_withdraw == 0)
                 join l in dbcontext.ADZ_GoodsLabel.Where(t => t.end_time < exptime)
                 on m.goods_id equals l.goods_id
                 select new
                 {
                     m.MPN,
                     m.goods_id,
                     l.label_type,
                     l.end_time
                 }).ToList();

            if (goodsList.Any())
            {
                var dicTypeName = ReleaseBiz.GetLabelTypeNameDic();
                var dicGoods = new Dictionary<string, int>();
                foreach (var dicitem in dicTypeName)
                {
                    int counts = goodsList.Count(t => t.label_type.ToString() == dicitem.Key);
                    if (counts > 0)
                        dicGoods.Add(dicitem.Key, counts);
                }

                string stroutmsg = "";
                foreach (var item in dicGoods)
                {
                    stroutmsg += $"{dicTypeName[item.Key]}板块有{item.Value}条库存将在3天内自动下架，请及时处理。 \t ";
                }
                if (stroutmsg.Length > 0)
                {
                    //发送业务消息
                    BusinessMsgBiz.Instance.SendBusinessMsg(new ADZ_BusinessMsg
                    {
                        BusinessMsgType = (int)BusinessMsgEnum.WidthUpDown,
                        msg = stroutmsg,
                        msg_title = "物料自动下架",
                        msg_url = $""
                    });
                }
            }
        }
    }
}
